package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    /**
     * 过滤器执行的逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径
        String path = request.getURI().getPath();

        //判断请求路径是否需要鉴权，这里判断路径中是否包含"/login"
        //如果包含，直接放行
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        //否则判断请求头是否携带token
        String token = request.getHeaders().getFirst("token");
        //有token，使用jwt工具解析token
        if (!StringUtils.isEmpty(token)) {
            try {
                //解析成功
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);
                //判断token是否有效
                int status = AppJwtUtil.verifyToken(claimsBody);
                if (status == -1 || status == 0) {
                    //token有效的话，从token中获取userId，放入到请求投中转发给后端的微服务
                    Object userId = claimsBody.get("userId");
                    request.mutate().header("userId", userId.toString());
                    //转发给后端微服务
                    return chain.filter(exchange);
                }
            } catch (Exception e) {
                //记录错误异常日志
                log.error(e.getMessage());
            }
        }
        //解析失败
        //没有token返回401 为授权状态
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序，数值越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
